package conf

import (
	"flag"
	"log"
	"os"
	"strings"
)

// Conf 配置参数
var Conf *Config

var (
	mongoAddr = flag.String("mongoAddr", "10.8.8.8", "mongo server address")

	redisAddr = flag.String("redisAddr", "10.8.8.8:6379", "redis server address")
	redisPwd  = flag.String("redisPwd", "", "redis password")
	redisDb   = flag.Int("redisDb", 0, "redis database")
	redisPool = flag.Int("redisPool", 5, "redis pool")

	zkAddr = flag.String("zkAddr", "10.8.8.8:2181", "zookeeper address")

	base   = flag.String("base", "/dawn_rpc", "prefix path")
	member = flag.String("member", "127.0.0.1:18800", "rpc member address")
)

// Config 配置 结构体
type Config struct {
	MongoAddr     string `yaml:"mongo_addr"`
	RedisAddr     string `yaml:"redis_addr"`
	RedisPwd      string `yaml:"redis_pwd"`
	RedisDb       int    `yaml:"redis_db"`
	RedisPool     int    `yaml:"redis_pool"`
	ZkAddr        string `yaml:"zk_addr"`
	RPCBasePath   string `yaml:"rpc_base_path"`
	RPCMemberAddr string `yaml:"rpc_member_addr"`
}

func init() {
	// path, err := handelPath()
	// if err != nil {
	// 	log.Fatal(err)
	// }
	// yamlFile, err := ioutil.ReadFile(path + "/dawn/conf/conf.yaml")
	// if err != nil {
	// 	log.Printf("yamlFile.Get err   #%v ", err)
	// }
	// err = yaml.Unmarshal(yamlFile, &Conf)
	// if err != nil {
	// 	log.Fatalf("Unmarshal: %v", err)
	// }
	// log.Printf("------ 参数为: %v", Conf)

	c := Config{"10.8.8.8", "10.8.8.8:6379", "", 0, 5, "10.8.8.8:2181", "/dawn_rpc", "127.0.0.1:18800"}
	Conf = &c
}

func handelPath() (string, error) {
	path, err := currPath()
	if err != nil {
		return "", err
	}

	path = parentPath(path)
	log.Printf("------ 现在路径: %s", path)
	return path, nil
}

func currPath() (string, error) {
	// dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	dir, err := os.Getwd()
	if err != nil {
		return "", err
	}
	log.Printf("------ 原始路径: %s", dir)
	return strings.Replace(dir, "\\", "/", -1), nil
}

func substr(s string, pos, length int) string {
	runes := []rune(s)
	l := pos + length
	if l > len(runes) {
		l = len(runes)
	}
	return string(runes[pos:l])
}

func parentPath(dirctory string) string {
	return substr(dirctory, 0, strings.LastIndex(dirctory, "/dawn"))
}
